#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <pthread.h>

using namespace std;

pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;//条件变量
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;//互斥锁
void *MasterCore(void *args)
{
    string name = static_cast<char *>(args);
    while (true)
    {
        sleep(3);
        cout << "Master开始工作.."<<endl;
        //将线程一个一个唤醒
        pthread_cond_signal(&gcond);
        cout<<"唤醒一个线程："<<endl;
        sleep(1);
    }
    return nullptr;
}
void *SlaverCore(void *args)
{
    string name = static_cast<char *>(args);
    while (true)
    {
        //加锁
        pthread_mutex_lock(&gmutex);
        //设置条件变量，让线程在等待队列
        pthread_cond_wait(&gcond, &gmutex);
        cout << "线程在等待：" << name<<endl;
        //解锁
        pthread_mutex_unlock(&gmutex);
    }
    return nullptr;
}

void StartSlaver(vector<pthread_t> *tidptr, int num)
{
    for (int i = 0; i < num; i++)
    {
        pthread_t tid;
        char *name = new char[64];
        snprintf(name, 64, "thread-%d", i + 1);
        int n = pthread_create(&tid, nullptr, SlaverCore, name);
        if (n == 0)
        {
            cout << "Slaver Thread create success" << endl;
        }
        tidptr->emplace_back(tid);
    }
}
void StartMaster(vector<pthread_t> *tidptr)
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, MasterCore, (void *)"MasterThread");
    if (n == 0)
    {
        cout << "Master Thread create success" << endl;
    }
    tidptr->emplace_back(tid);
}
void WaitThread(vector<pthread_t> tidptr)
{
    for(auto& tid:tidptr)
    {
        pthread_join(tid, nullptr);
    }
}
int main()
{
    vector<pthread_t> tids;
    StartMaster(&tids);
    StartSlaver(&tids, 5);
    WaitThread(tids);
    return 0;
}